package org.study.swing.study02.demo;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

public class MyDialog extends JDialog implements ActionListener {
    private static final long serialVersionUID = 1L;

    private Connect dbconn = new Connect();
    private static String id;
    private JPanel pCenter, pSouth;
    private JLabel nameLab, sexLab, mailLab, salaryLab, phoneLab, didLab;
    private JTextField nameText, mailText, salaryText, phoneText, didText;
    private JComboBox<String> sex;
    private JButton yesBtn, noBtn;

    public MyDialog(String title, Map<String, String> info) {
        id = info.get("id");
        if ("删除信息".equals(title)) {
            deletePerson();
        } else {
            Font font = new Font("宋体", Font.BOLD, 14);
            // 下拉列表组件添加内容
            String[] sexType = {"-请选择-", "男", "女"};
            pCenter = new JPanel();
            pCenter.setLayout(new GridLayout(5, 1));
            nameLab = new JLabel("姓名：");
            sexLab = new JLabel("性别：");
            mailLab = new JLabel("工号：");
            salaryLab = new JLabel("薪资：");
            phoneLab = new JLabel("电话：");
            didLab = new JLabel("部门：");
            nameLab.setFont(font);
            sexLab.setFont(font);
            mailLab.setFont(font);
            salaryLab.setFont(font);
            phoneLab.setFont(font);
            didLab.setFont(font);
            nameText = new JTextField(10);
            mailText = new JTextField(10);
            salaryText = new JTextField(10);
            phoneText = new JTextField(10);
            didText = new JTextField(10);
            sex = new JComboBox<String>(sexType);

            JPanel jp1 = new JPanel();
            jp1.setLayout(new FlowLayout(FlowLayout.LEFT));
            jp1.add(nameLab);
            jp1.add(nameText);

            JPanel jp5 = new JPanel();
            jp5.setLayout(new FlowLayout(FlowLayout.LEFT));
            jp5.add(sexLab);
            jp5.add(sex);
            nameText.setText(info.get("name"));
            sex.setSelectedItem(info.get("sex"));

            JPanel jp2 = new JPanel();
            jp2.setLayout(new FlowLayout(FlowLayout.LEFT));
            jp2.add(mailLab);
            jp2.add(mailText);
            mailText.setText(info.get("worknumber"));

            JPanel jp3 = new JPanel();
            jp3.setLayout(new FlowLayout(FlowLayout.LEFT));
            jp3.add(salaryLab);
            jp3.add(salaryText);
            salaryText.setText(info.get("salary"));

            JPanel jp4 = new JPanel();
            jp4.setLayout(new FlowLayout(FlowLayout.LEFT));
            jp4.add(phoneLab);
            jp4.add(phoneText);
            phoneText.setText(info.get("telephone"));

            JPanel jp6 = new JPanel();
            jp6.setLayout(new FlowLayout(FlowLayout.LEFT));
            jp6.add(didLab);
            jp6.add(didText);
            didText.setText(info.get("did"));

            pCenter.add(jp1);
            pCenter.add(jp5);
            pCenter.add(jp2);
            pCenter.add(jp3);
            pCenter.add(jp4);
            pCenter.add(jp6);

            pSouth = new JPanel();
            yesBtn = new JButton("以数据库保存");
            yesBtn.addActionListener(this);
            noBtn = new JButton("以文件保存");
            noBtn.addActionListener(this);
            pSouth.add(yesBtn);
            pSouth.add(noBtn);

            this.add(pCenter, "Center");
            this.add(pSouth, "South");

            this.setTitle(title);
            this.setSize(400, 450);
            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // 系统功能按钮监听器
        if (e.getSource() == yesBtn) {
            if (this.getTitle().equals("新建员工信息")) {
                dbinsertPerson();
            } else if (this.getTitle().equals("修改员工信息")) {
                updatePerson();
            } else if (this.getTitle().equals("删除员工信息")) {
                deletePerson();
            }
        } else if (e.getSource() == noBtn) {
            fileinsertPerson();
        }
    }

    public void insertPerson() {
        if (nameText.getText().isEmpty()) {
            // 提示弹窗
            JOptionPane.showMessageDialog(null, "请输入姓名！");
        }
    }

    public void dbinsertPerson() {
        // 将新建的学生信息写入数据库的表中
        boolean flag = true;
        String sql = "insert into empinfo(name, sex, telephone, worknumber, salary, did)value(?,?,?,?,?,?)";
        try {
            // PreparedStatement 对象已预编译过，所以其执行速度要快于 Statement 对象,多次执行的 SQL 语句经常创建为 PreparedStatement 对象，以提高效率。作为 Statement 的子类，PreparedStatement 继承了 Statement 的所有功能
            PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);
            pstmt.setString(1, nameText.getText());
            pstmt.setString(2, (String) sex.getSelectedItem());
            pstmt.setString(3, phoneText.getText());
            pstmt.setString(4, mailText.getText());
            pstmt.setString(5, salaryText.getText());
            pstmt.setString(6, didText.getText());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            // 提示弹窗
            JOptionPane.showMessageDialog(null, "新建员工信息失败！");
            flag = false;
        } finally {
            dispose();
            if (flag) {
                // 提示弹窗
                JOptionPane.showMessageDialog(null, "新建员工信息成功！");
            }
            // 将数据写入数据库
            System.flashInfo();
            DefaultTableModel model = new DefaultTableModel(System.info, System.column);

            System.infoTable.setModel(model);
            TableColumn column1 = System.infoTable.getColumnModel().getColumn(0);
            column1.setMaxWidth(40);
            column1.setMinWidth(40);

            TableColumn column3 = System.infoTable.getColumnModel().getColumn(2);
            column3.setMaxWidth(40);
            column3.setMinWidth(40);
        }
    }

    public void fileinsertPerson() {// 将新建的学生信息写入文件中
        boolean flag = true;
        try {
            StringBuffer sbf = new StringBuffer();
            sbf.append(nameText.getText()).append(" ")
                    .append((String) sex.getSelectedItem()).append(" ")
                    .append(phoneText.getText()).append(" ")
                    .append(mailText.getText()).append(" ")
                    .append(salaryText.getText()).append(" ")
                    .append(didText.getText());
            File file = new File("information.txt");
            FileOutputStream fos = null;
            if (!file.exists()) {
                file.createNewFile();// 如果文件不存在，就创建该文件
                fos = new FileOutputStream(file);// 首次写入获取
            } else {
                // 如果文件已存在，就在文件末尾追加写入
                fos = new FileOutputStream(file, true);
            }
            OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");// 指定以UTF-8格式写入文件
            osw.write(sbf.toString());
            osw.write("\r\n");
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "新建员工信息失败！");// 提示弹窗
            flag = false;
        } finally {
            dispose();
            if (flag) {
                JOptionPane.showMessageDialog(null, "新建员工信息成功！");// 提示弹窗
            }
        }
    }

    public void deletePerson() {// 删除信息
        String sql = "delete from empinfo where id=?";

        try {
            // PreparedStatement 对象已预编译过，所以其执行速度要快于 Statement 对象,多次执行的 SQL 语句经常创建为 PreparedStatement 对象，以提高效率。作为 Statement 的子类，PreparedStatement 继承了 Statement 的所有功能
            PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);
            pstmt.setString(1, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dispose();
            System.flashInfo();
            DefaultTableModel model = new DefaultTableModel(System.info, System.column);
            JOptionPane.showMessageDialog(null, "删除成功！");
            System.infoTable.setModel(model);
            TableColumn column1 = System.infoTable.getColumnModel().getColumn(0);
            column1.setMaxWidth(40);
            column1.setMinWidth(40);

            TableColumn column3 = System.infoTable.getColumnModel().getColumn(2);
            column3.setMaxWidth(40);
            column3.setMinWidth(40);
        }
    }

    public void updatePerson() {// 修改信息
        if (nameText.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "请输入姓名！");// 提示弹窗
        }
        String sql = "update empinfo set name=?,sex=?,telephone=?,worknumber=?,salary=?,did=? where id=?";

        try {
            // PreparedStatement 对象已预编译过，所以其执行速度要快于 Statement 对象,多次执行的 SQL 语句经常创建为 PreparedStatement 对象，以提高效率。作为 Statement 的子类，PreparedStatement 继承了 Statement 的所有功能
            PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);
            pstmt.setString(1, nameText.getText());
            pstmt.setString(2, (String) sex.getSelectedItem());
            pstmt.setString(3, phoneText.getText());
            pstmt.setString(4, mailText.getText());
            pstmt.setString(5, salaryText.getText());
            pstmt.setString(6, didText.getText());
            pstmt.setString(7, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dispose();
            System.flashInfo();
            DefaultTableModel model = new DefaultTableModel(System.info, System.column);

            System.infoTable.setModel(model);
            TableColumn column1 = System.infoTable.getColumnModel().getColumn(0);
            column1.setMaxWidth(40);
            column1.setMinWidth(40);

            TableColumn column3 = System.infoTable.getColumnModel().getColumn(2);
            column3.setMaxWidth(40);
            column3.setMinWidth(40);
        }
    }
}